class Im
  APP_KEY = 'ab178896995f3eec13a7edd44fd71707'
  APP_SEC = '89fa49bdb4ac'
  BASE_URL = 'https://api.netease.im/nimserver'

  def self.get_post_header
    num = rand(100000)
    time = Time.now.to_i
    check_num = Digest::SHA1.hexdigest("#{APP_SEC}#{num}#{time}")
    {
        'AppKey' => APP_KEY,
        :content_type => 'application/x-www-form-urlencoded;charset=utf-8',
        'Nonce' => num,
        'CurTime' => time,
        'CheckSum' => check_num
    }
  end

  def self.q(from, to, end_time=Time.now)
    attrs ||= {
        from: from,
        to: to,
        begintime: (end_time-7.days).to_i * 1000,
        endtime: end_time.to_i * 1000,
        limit: 100
    }
    url = 'https://api.netease.im/nimserver/history/querySessionMsg.action'
    r = JSON.parse RestClient.post(url, attrs, Im.get_post_header)
    r['msgs'].each do |x|
      puts [
               Time.at(x['sendtime']/1000).label,
               x['from'],
               (x['body']['msg'] rescue x['body'])
           ].join("\t")
    end.length
  end
end